package com.sinosoft.vaccinetoai.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author xiazhihao
 * @ClassName: HttpUtils
 * @ClassNameExplain:
 * @Description Https请求方式封装
 * @date 2024/12/3 23:12
 */
public class HttpUtils {

    /**
     * 发送 GET 请求
     * @param url 请求的 URL 地址
     * @return 响应字符串
     * @throws IOException 请求或响应异常
     */
    public static String doGet(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json");
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            return handleResponse(response);
        }
    }

    /**
     * 发送 POST 请求
     * @param url 请求的 URL 地址
     * @param body 请求体 JSON 字符串
     * @return 响应字符串
     * @throws IOException 请求或响应异常
     */
    public static String doPost(String url, String body) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        if (body != null) {
            StringEntity entity = new StringEntity(body, "UTF-8");
            httpPost.setEntity(entity);
        }
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            return handleResponse(response);
        }
    }

    /**
     * 处理响应
     * @param response HttpResponse 对象
     * @return 响应体字符串
     * @throws IOException 读取响应体时发生异常
     */
    private static String handleResponse(HttpResponse response) throws IOException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            return EntityUtils.toString(entity, "UTF-8");
        }
        return null;
    }
}
